package com.dianshang.service.impl;

import com.alibaba.dubbo.config.annotation.Service;
import com.dianshang.dao.AdminDao;
import com.dianshang.dao.LoginLogDao;
import com.dianshang.entity.PageResult;
import com.dianshang.pojo.system.Admin;
import com.dianshang.pojo.system.LoginLog;
import com.dianshang.service.system.LoginLogService;
import com.dianshang.utils.BCrypt;
import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import org.springframework.beans.factory.annotation.Autowired;
import tk.mybatis.mapper.entity.Example;

import java.util.List;

@Service
public class LoginLogServiceImpl implements LoginLogService {

    @Autowired
    private LoginLogDao loginLogDao;

    @Autowired
    private AdminDao adminDao;

    /**
     * 登录日志处理
     */
    public void insert(LoginLog loginLog) {
        loginLogDao.insert(loginLog);
    }

    /**
     * 查询我的登录日志列表
     */
    public PageResult<LoginLog> findPage(String name,
                                         Integer page,
                                         Integer size) {
        PageHelper.startPage(page, size);
        // 获得用户
        Example example = new Example(LoginLog.class);
        Example.Criteria criteria = example.createCriteria();
        criteria.andEqualTo("loginName", name); // 登录用户
        Page<LoginLog> list =(Page<LoginLog>) loginLogDao.selectByExample(example);
        return new PageResult<LoginLog>(list.getTotal(), list.getResult());
    }

    /**
     * 修改密码
     */
    public void changePwd(String name, String pwd) {
        // 获得用户
        Example example = new Example(LoginLog.class);
        Example.Criteria criteria = example.createCriteria();
        criteria.andEqualTo("loginName", name); // 登录用户
        List<Admin> list = adminDao.selectByExample(example);
        Admin admin = list.get(0);
        // BCrypt加密：
        //      盐：BCrypt.gensalt()
        //      根据盐对密码进行加密
        admin.setPassword(BCrypt.hashpw(pwd, BCrypt.gensalt()));
        adminDao.updateByPrimaryKeySelective(admin);
    }

}